package com.goatrock.media.thisway.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.apache.log4j.Logger;

public class FileHandlers {
    public static Logger logger = Logger.getLogger(FileHandlers.class);

    public static boolean copyFile(File src, File dst){
        boolean success = true;

        try{
            logger.debug("Attempting to copy file:"+src.getAbsolutePath()+" to:"+dst.getAbsolutePath());
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dst);

            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
        }catch(FileNotFoundException e){
            logger.error("FileNotFoundException while trying to copy: "+src.getAbsolutePath()+ " to: "+dst.getAbsolutePath());
            success = false;
        }catch(IOException e){
            logger.error("IOException while trying to copy: "+src.getAbsolutePath()+ " to: "+dst.getAbsolutePath());
            success = false;
        }
        
        return success;
    }

    public static File retrieveClasspathResource(String loc){
        logger.debug("Attempting to retrieve classpath resource: "+loc);
        ApplicationContext ctx = new FileSystemXmlApplicationContext();
        File file = null;

        Resource res = ctx.getResource(loc);

        try{
            file = res.getFile();
        }catch(IOException e){
            logger.error("Was not able to retrieve classpath resource: "+e.getMessage());
        }

        return file;
    }

}
